//
//  OxModel.m
//  project
//
//  Created by 黄建华 on 2018/2/6.
//  Copyright © 2018年 黄建华. All rights reserved.
//

#import "OxModel.h"

/***************************************************血氧模型***********************************************/
@implementation oxSubModel
- (instancetype)init {
    self = [super init];
    if (self) {
    }
    return self;
}

@end

@implementation OxModel

- (instancetype)init {
    self = [super init];
    if (self) {
        _user_id    = SN_USER.user_id;
        _dateString = [[NSDate date] dateToDayString];
        _oxAve      = 0;
        _oxMax      = 0;
        _oxMin      = 0;
        _weekCount  = [NSDate getDaysWeekNumberWithSelectDate:[NSDate date]];
        _monthCount = [NSDate getDaysMonthNumberWithSelectDate:[NSDate date]];
        _dayOfWeek  = [NSDate getDaysYearNumberWithSelectDate:[NSDate date] withType:0];
        _dayOfMonth = [NSDate getDaysYearNumberWithSelectDate:[NSDate date] withType:1];
        _yearCount  = [NSDate getDaysYearNumberWithSelectDate:[NSDate date] withType:2];
    }
    return self;
}

+ (OxModel *)initWithDate:(NSDate *)date {
    OxModel *model = [[OxModel alloc] init];
    
    model.dateString = [date dateToDayString];
    model.user_id    = SN_USER.user_id;
    model.oxAve      = 0;
    model.oxMax      = 0;
    model.oxMin      = 0;
    model.weekCount  = [NSDate getDaysWeekNumberWithSelectDate:date];
    model.monthCount = [NSDate getDaysMonthNumberWithSelectDate:date];
    model.dayOfWeek  = [NSDate getDaysYearNumberWithSelectDate:date withType:0];
    model.dayOfMonth = [NSDate getDaysYearNumberWithSelectDate:date withType:1];
    model.yearCount  = [NSDate getDaysYearNumberWithSelectDate:date withType:2];
    return model;
}

+ (OxModel *)getOxModelFromDB {
    OxModel *model = [OxModel getOxModelFromDBWith:[NSDate date]];
    
    return model;
}

+ (OxModel *)getOxModelFromDBWithDayString:(NSString *)string {
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString = '%@'",
                       SN_USER.user_id, string];
    OxModel *model = [OxModel searchSingleWithWhere:where orderBy:nil];
    
    if (!model) {
        model            = [[OxModel alloc] init];
        model.dateString = string;
        model.user_id    = SN_USER.user_id;
        NSDate    *date= [NSDate dateByString:string];
        model.weekCount  = [NSDate getDaysWeekNumberWithSelectDate:date];
        model.monthCount = [NSDate getDaysMonthNumberWithSelectDate:date];
        model.dayOfWeek  = [NSDate getDaysYearNumberWithSelectDate:date withType:0];
        model.dayOfMonth = [NSDate getDaysYearNumberWithSelectDate:date withType:1];
        model.yearCount  = [NSDate getDaysYearNumberWithSelectDate:date withType:2];
        [model updateToDB];
    }
    return model;
}

+ (OxModel *)getOxModelFromDBWith:(NSDate *)date {
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString = '%@'",
                       SN_USER.user_id, [date dateToDayString]];
    OxModel *model = [OxModel searchSingleWithWhere:where orderBy:nil];
    
    if (!model) {
        model = [OxModel pedometerSaveEmptyModelToDBWithDate:date isSaveAllDay:NO];
    }
    return model;
}

- (void)updateToDBSafely {
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString = '%@'",
                       SN_USER.user_id, self.dateString];
    OxModel *model = [OxModel searchSingleWithWhere:where orderBy:nil];
    
    if (model) {
        [OxModel updateToDB:self where:nil];
    }
}

+ (OxModel *)pedometerSaveEmptyModelToDBWithDate:(NSDate *)date isSaveAllDay:(BOOL)save {
    OxModel *model = [OxModel initWithDate:date];
    
    [OxModel creatEmptyDataArrayWithModel:model];
    if (![date compareWithDate:[NSDate date]] &&
        [date timeIntervalSince1970] < [[NSDate date] timeIntervalSince1970]) {
        // NSLog(@"model.isSaveAllDay = ..%@", date);
        if (save) {
            model.isSaveAllDay = YES;
        }
    }
    [model saveToDB];
    return model;
}

// 为模型创建空值的对象
+ (void)creatEmptyDataArrayWithModel:(OxModel *)model {
}

// 表名
+ (NSString *)getTableName {
    return @"OxModel";
}

// 复合主键
+ (NSArray *)getPrimaryKeyUnionArray {
    return @[@"user_id", @"dateString"];
}

// 表版本
+ (int)getTableVersion {
    return 1;
}

+ (void)initialize {
    [super initialize];
    
    [self bindYYJSONKey:@"average" toProperty:@"oxAve"];
    [self bindYYJSONKey:@"max" toProperty:@"oxMax"];
    [self bindYYJSONKey:@"min" toProperty:@"oxMin"];
    [self bindYYJSONKey:@"data" toProperty:@"detailData"];
    [self bindYYJSONKey:@"date" toProperty:@"dateString"];
    
    [self removePropertyWithColumnName:@"detailData"];
}

// 手动同步完之后 血氧
+ (void)updateCheckOX {
    NSLog(@"手动检测血氧数据同步完成>>>");
    [SN_Net updateEveryModelWithType:HJUpdateOX];
}

- (void)updateRealOXData:(NSInteger)OX {
    [SN_PublicClass.oXCheckArray addObject:StrByInt(OX)];
    SN_PublicClass.oxValueString = StrByInt(OX);
    if (SN_PublicClass.oxBlock) {
        SN_PublicClass.oxBlock(OX);
    }
}

- (void)updateRealOXEnd:(NSArray *)oxArray {
    NSLog(@"updateRealOXEnd: >>>>>%@", oxArray);
    
    SN_PublicClass.oXCheckArray = [NSMutableArray array];
    [SN_PublicClass.oXCheckArray addObjectsFromArray:oxArray];
    
    int             total  = 0;
    NSMutableString *DataS = [NSMutableString string];
    for (NSString *oxS in SN_PublicClass.oXCheckArray) {
        total += oxS.intValue;
        [DataS appendString:oxS];
        [DataS appendString:@","];
    }
    oxSubModel *oxModel = [[oxSubModel alloc] init];
    oxModel.oxValue = total / SN_PublicClass.oXCheckArray.count;
    oxModel.count   = [NSDate getCurrentMinTotal]/15;
    int currentMin = [NSDate getCurrentMinTotal];
    oxModel.countMins = currentMin;
    NSDate *nowDate      = [NSDate date];//现在的UTC时间也可以写成[[NSDate alloc] init];
    NSDate *startOfToday = [[NSCalendar currentCalendar] startOfDayForDate:nowDate];
    
    NSDate   *date = [startOfToday dateByAddingTimeInterval:currentMin *60];
    NSString *time = [date dateToStringHourMin];
    oxModel.updateTime = time;
    //            oxModel.data       = DataS;
    
    OxModel        *tmodel     = SN_PublicClass.todayOx;
    NSMutableArray *checkArray = [NSMutableArray arrayWithArray:tmodel.oxsuArrayAuto];
    [checkArray addObject:oxModel];
    NSMutableArray *array = [NSMutableArray array];
    
    for (int i = 0; i < checkArray.count; i++) {
        oxSubModel *oxModel = [checkArray objectAtIndex:i];
        [array addObject:[NSString stringWithFormat:@"%d", oxModel.oxValue]];
    }
    
    CGFloat max = [[array valueForKeyPath:@"@max.floatValue"] floatValue];
    CGFloat min = [[array valueForKeyPath:@"@min.floatValue"] floatValue];
    float   avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];//求平均值
    tmodel.oxAve         = (NSUInteger)avg;
    tmodel.oxMax         = max;
    tmodel.oxMin         = min;
    tmodel.oxsuArrayAuto = [NSMutableArray arrayWithArray:checkArray];
    [tmodel updateToDB];
}

//同步下载数据需要的
- (void)saveToDBByDownload
{
    NSDate *date= [NSDate dateByString:self.dateString];
    self.weekCount  = [NSDate getDaysWeekNumberWithSelectDate:date];
    self.monthCount = [NSDate getDaysMonthNumberWithSelectDate:date];
    self.dayOfWeek  = [NSDate getDaysYearNumberWithSelectDate:date withType:0];
    self.dayOfMonth = [NSDate getDaysYearNumberWithSelectDate:date withType:1];
    self.yearCount  = [NSDate getDaysYearNumberWithSelectDate:date withType:2];
    
    NSArray *array = (NSArray *)[self.detailData parseJSONString];
    if ([array isKindOfClass:NSArray.class] && array.count > 0) {
        self.oxsuArrayAuto = [NSMutableArray array];
        for (int i = 0; i < array.count ; i++) {
            NSDictionary *dict = array[i];
            if ([dict isKindOfClass:NSDictionary.class]) {
                if (dict[@"value"] && dict[@"time"]) {
                    oxSubModel *model = [[oxSubModel alloc] init];
                    model.oxValue = [dict[@"value"] integerValue];
                    NSString *time = @"";
                    NSArray *timeArrayS = [dict[@"time"] componentsSeparatedByString:@" "];
                    if (timeArrayS.count ==2) {
                        model.updateTime = dict[@"time"];
                        time = [timeArrayS lastObject];
                    }
                    else
                    {
                        NSString *updateTimeString = [NSString stringWithFormat:@"%@ %@",self.dateString,dict[@"time"]];
                        model.updateTime = updateTimeString;
                        time = dict[@"time"];
                        
                    }
                    
                    NSString *timeS     = time;
                    NSString *timeSS = @"";
                    if (timeS.length >=5) {
                        timeSS = [timeS substringWithRange:NSMakeRange(0, 5)];
                    }
                    else
                    {
                        timeSS = [timeS substringWithRange:NSMakeRange(0, timeS.length)];
                    }
                    NSArray *timeArray = [timeSS componentsSeparatedByString:@":"];
                    int timeInt = [[timeArray firstObject]intValue]*60 +[[timeArray lastObject]intValue];
                    model.count = timeInt/15;
                    model.countMins = timeInt;
                    [self.oxsuArrayAuto addObject:model];
                }
            }
        }
    }
    
    NSMutableArray *arraySum = [NSMutableArray array];
    
    for (int i = 0; i < self.oxsuArrayAuto.count; i++) {
        oxSubModel *oxModel = [self.oxsuArrayAuto objectAtIndex:i];
        [arraySum addObject:[NSString stringWithFormat:@"%d", oxModel.oxValue]];
    }
    
    CGFloat max = [[arraySum valueForKeyPath:@"@max.floatValue"] floatValue];
    CGFloat min = [[arraySum valueForKeyPath:@"@min.floatValue"] floatValue];
    float   avg = [[arraySum valueForKeyPath:@"@avg.floatValue"] floatValue];//求平均值
    self.oxAve         = (NSUInteger)avg;
    self.oxMax         = max;
    self.oxMin         = min;
    
    NSString *todayStr = [[NSDate date] dateToDayString];
    if (self.dateString != todayStr) {
        self.isSaveAllDay = YES;
    }
    
    [self updateToDB];
}

@end

